<template>
  <div class="customer-management">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><User /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ customerStats.total }}</div>
                <div class="stats-label">总客户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon new">
                <el-icon><Plus /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ customerStats.newToday }}</div>
                <div class="stats-label">今日新增</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon active">
                <el-icon><Star /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ customerStats.active }}</div>
                <div class="stats-label">活跃客户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon vip">
                <el-icon><Crown /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ customerStats.vip }}</div>
                <div class="stats-label">VIP客户</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和操作栏 -->
    <el-card shadow="never" class="search-card">
      <div class="search-container">
        <div class="search-left">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索客户姓名、手机号"
            style="width: 300px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="searchForm.status" placeholder="客户状态" style="width: 150px" clearable>
            <el-option label="全部" value="" />
            <el-option label="正常" value="NORMAL" />
            <el-option label="VIP" value="VIP" />
            <el-option label="黑名单" value="BLACKLIST" />
          </el-select>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
        <div class="search-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加客户
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 客户列表 -->
    <el-card shadow="never">
      <el-table
        :data="customerList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="客户信息" min-width="200">
          <template #default="{ row }">
            <div class="customer-info">
              <el-avatar :src="row.avatar" :size="40">
                {{ row.name?.charAt(0) }}
              </el-avatar>
              <div class="customer-detail">
                <div class="customer-name">
                  {{ row.name }}
                  <el-tag v-if="row.level === 'VIP'" type="warning" size="small">VIP</el-tag>
                </div>
                <div class="customer-phone">{{ row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <span>{{ row.gender === 'MALE' ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="totalOrders" label="历史订单" width="100" />
        <el-table-column prop="totalAmount" label="消费金额" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastOrderTime" label="最后下单" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-dropdown>
              <el-button type="primary" link>
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleViewOrders(row)">
                    <el-icon><Document /></el-icon>查看订单
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleSetVip(row)" v-if="row.level !== 'VIP'">
                    <el-icon><Crown /></el-icon>设为VIP
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleBlacklist(row)" divided>
                    <el-icon><Lock /></el-icon>加入黑名单
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 客户详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="customerFormRef"
        :model="customerForm"
        :rules="customerFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="customerForm.name" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="customerForm.phone" :disabled="isView" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="customerForm.gender" :disabled="isView">
                <el-radio label="MALE">男</el-radio>
                <el-radio label="FEMALE">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户等级" prop="level">
              <el-select v-model="customerForm.level" :disabled="isView">
                <el-option label="普通客户" value="NORMAL" />
                <el-option label="VIP客户" value="VIP" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="customerForm.address"
            type="textarea"
            :rows="3"
            :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="customerForm.remark"
            type="textarea"
            :rows="3"
            :disabled="isView"
          />
        </el-form-item>
      </el-form>
      <template #footer v-if="!isView">
        <el-button @click="detailVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const customerList = ref([])
const selectedCustomers = ref([])
const detailVisible = ref(false)
const isView = ref(false)
const dialogTitle = ref('')

// 统计数据
const customerStats = ref({
  total: 1268,
  newToday: 23,
  active: 956,
  vip: 89
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 客户表单
const customerForm = reactive({
  id: null,
  name: '',
  phone: '',
  gender: 'MALE',
  level: 'NORMAL',
  address: '',
  remark: ''
})

// 表单验证规则
const customerFormRules = {
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const customerFormRef = ref()

// 模拟数据
const mockCustomerList = [
  {
    id: 1,
    name: '张女士',
    phone: '13800138001',
    gender: 'FEMALE',
    level: 'VIP',
    address: '北京市朝阳区某某小区1号楼',
    totalOrders: 25,
    totalAmount: 3680,
    lastOrderTime: '2024-01-10',
    status: 'NORMAL',
    createTime: '2023-06-15',
    remark: ''
  },
  {
    id: 2,
    name: '李先生',
    phone: '13800138002',
    gender: 'MALE',
    level: 'NORMAL',
    address: '北京市海淀区某某大厦A座',
    totalOrders: 12,
    totalAmount: 1560,
    lastOrderTime: '2024-01-08',
    status: 'NORMAL',
    createTime: '2023-08-20',
    remark: ''
  }
]

// 获取客户列表
const fetchCustomerList = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    customerList.value = mockCustomerList
    pagination.total = mockCustomerList.length
  } catch (error) {
    ElMessage.error('获取客户列表失败')
  } finally {
    loading.value = false
  }
}

// 状态类型
const getStatusType = (status) => {
  const types = {
    'NORMAL': '',
    'VIP': 'warning',
    'BLACKLIST': 'danger'
  }
  return types[status] || ''
}

// 状态文本
const getStatusText = (status) => {
  const texts = {
    'NORMAL': '正常',
    'VIP': 'VIP',
    'BLACKLIST': '黑名单'
  }
  return texts[status] || '未知'
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchCustomerList()
}

// 添加客户
const handleAdd = () => {
  isView.value = false
  dialogTitle.value = '添加客户'
  resetForm()
  detailVisible.value = true
}

// 查看客户
const handleView = (row) => {
  isView.value = true
  dialogTitle.value = '客户详情'
  fillForm(row)
  detailVisible.value = true
}

// 编辑客户
const handleEdit = (row) => {
  isView.value = false
  dialogTitle.value = '编辑客户'
  fillForm(row)
  detailVisible.value = true
}

// 查看订单
const handleViewOrders = (row) => {
  ElMessage.info('跳转到客户订单页面')
}

// 设为VIP
const handleSetVip = async (row) => {
  try {
    await ElMessageBox.confirm('确认将该客户设为VIP吗？', '提示', {
      type: 'warning'
    })
    ElMessage.success('设置成功')
    fetchCustomerList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('设置失败')
    }
  }
}

// 加入黑名单
const handleBlacklist = async (row) => {
  try {
    await ElMessageBox.confirm('确认将该客户加入黑名单吗？', '警告', {
      type: 'warning'
    })
    ElMessage.success('操作成功')
    fetchCustomerList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedCustomers.value = selection
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchCustomerList()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchCustomerList()
}

// 表单操作
const resetForm = () => {
  Object.assign(customerForm, {
    id: null,
    name: '',
    phone: '',
    gender: 'MALE',
    level: 'NORMAL',
    address: '',
    remark: ''
  })
}

const fillForm = (row) => {
  Object.assign(customerForm, row)
}

const handleSubmit = async () => {
  try {
    await customerFormRef.value.validate()
    submitLoading.value = true
    
    if (customerForm.id) {
      ElMessage.success('更新成功')
    } else {
      ElMessage.success('添加成功')
    }
    
    detailVisible.value = false
    fetchCustomerList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  customerFormRef.value?.resetFields()
}

// 页面加载
onMounted(() => {
  fetchCustomerList()
})
</script>

<style scoped>
.customer-management {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  overflow: hidden;
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stats-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.new {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.active {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.vip {
  background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-left {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-right {
  display: flex;
  gap: 12px;
}

.customer-info {
  display: flex;
  align-items: center;
}

.customer-detail {
  margin-left: 12px;
}

.customer-name {
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.customer-phone {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.amount {
  font-weight: 500;
  color: #f56c6c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}
</style> 